<?php
use App\Exceptions\Error;

if (!function_exists('config_path')) {
    /**
     * Get the configuration path.
     *
     * @param  string $path
     * @return string
     */
    function config_path($path = '')
    {
        return app()->basePath() . '/config' . ($path ? '/' . $path : $path);
    }
}

/**
 * 返回成功
 */
if (! function_exists('success')) {
    function success(array $data = [])
    {
        $response =
            [
                'code' => 200,
                'timestamps ' => date('Y-m-d H:i', time()),
                'data' => $data
            ];

        // 开发环境检测运行时间
        if (config('app.env') === 'dev') {

            // 返回运行时间
            $response = array_merge($response, ['runtime' => round(microtime(true) - LUMEN_START, 2)]);
            $maxRuntime = 1;

            // 大于运行运行时间记录日志
            if ($response['runtime'] > $maxRuntime) {
                $Request = \Illuminate\Support\Facades\Request::instance();
                \Illuminate\Support\Facades\Log::stack(['runtime'])->info('runtime > '.$maxRuntime.'s', [
                    '请求方式' => $Request->method(),
                    '请求路由' => $Request->path(),
                    '运行时间' => $response['runtime'],
                    '请求参数' => $Request->input(),
                ]);
            }
        }

        \Illuminate\Support\Facades\Log::debug('Response Success', $response);

        return response()->json($response);
    }
}

/**
 * 返回错误
 */
if (! function_exists('error')) {
    function error($code, $args = [], $statusCode = 500)
    {

        $message = empty(config('code.'.$code)) ? '未知的错误' : config('code.'.$code);

        if (!empty($args)) {
            $message = vsprintf($message, $args);
        }

        throw new Error($code, $message, $statusCode);
    }
}